﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using SIMSProject.Helpers;
using SIMSProject.Helpers.QuickLaunch;
using SIMSProject.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace SIMSProject.WebParts
{
    public class QuickLaunchItemWebPart : WebPart
    {
        private string pageTitle;
        private TextBox txtUrl;
        private TextBox txtDescription;
        private DropDownList ddlHeading;
        private Button btnOk;
        private Button btnCancel;
        private Button btnDelete;
        private PropertySheet propertySheet;

        private PropertySheetSection urlSection;
        private PropertySheetControl urlSectionControl;
        private PropertySheetControl descriptionSectionControl;
        
        private PropertySheetSection headingSection;
        private PropertySheetControl headingSectionControl;

        private PropertySheetSection otherSection;

        private TextBox txtPosition;
        private PropertySheetControl positionSectionControl;

        private FormDigest formDigest;

        public override PartChromeType ChromeType
        {
            get { return PartChromeType.None; }
            set { base.ChromeType = value; }
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            propertySheet = new PropertySheet();
            Controls.Add(propertySheet);

            urlSection = new PropertySheetSection { Header = LocalizationHelper.GetString("wss", "nav_url") };
            propertySheet.AddSection(urlSection);

            txtUrl = new TextBox { ToolTip = LocalizationHelper.GetString("wss", "nav_url"), CssClass = "ms-long", MaxLength = 255, Text = "http://" };
            Controls.Add(txtUrl);

            urlSectionControl = new PropertySheetControl(LocalizationHelper.GetString("wss", "form_type_web_address"), txtUrl);
            urlSection.SectionControls.Add(urlSectionControl);

            txtDescription = new TextBox { ToolTip = LocalizationHelper.GetString("wss", "nav_desc"), CssClass = "ms-long", MaxLength = 255 };
            Controls.Add(txtDescription);

            descriptionSectionControl = new PropertySheetControl(LocalizationHelper.GetString("wss", "form_type_description"), txtDescription);
            urlSection.SectionControls.Add(descriptionSectionControl);

            if (string.IsNullOrEmpty(Page.Request.QueryString["ParentId"]))
            {
                ddlHeading = new DropDownList
                                 {
                                     ToolTip = LocalizationHelper.GetString("wss", "nav_cat"),
                                     DataSource = QuickLaunchManager.GetAllQuickLaunchHeading(SPContext.Current.Web),
                                     DataValueField = "Id",
                                     DataTextField = "Title"
                                 };
                ddlHeading.DataBind();
                Controls.Add(ddlHeading);

                headingSectionControl = new PropertySheetControl("", ddlHeading);
                headingSection = new PropertySheetSection { Header = LocalizationHelper.GetString("wss", "nav_cat") };
                headingSection.SectionControls.Add(headingSectionControl);
                propertySheet.AddSection(headingSection);
            }

            otherSection = new PropertySheetSection { Header = LocalizationHelper.GetString("QuickLaunchItemWebPart_MS001") };
            propertySheet.AddSection(otherSection);

            txtPosition = new TextBox {CssClass = "ms-input"};
            Controls.Add(txtPosition);
            positionSectionControl = new PropertySheetControl(LocalizationHelper.GetString("QuickLaunchItemWebPart_MS002"), txtPosition);
            otherSection.SectionControls.Add(positionSectionControl);

            if (!string.IsNullOrEmpty(Page.Request.QueryString["Id"]))
            {
                btnDelete = new Button
                                {
                                    ID = "btnDelete",
                                    CssClass = "ms-ButtonHeightWidth",
                                    Text = LocalizationHelper.GetString("wss", "fldedit_delete"),
                                    UseSubmitBehavior = false,
                                    OnClientClick = string.Format("if(!confirm('{0}')) return;", LocalizationHelper.GetString("wss", "newnav_deletenodewarning"))
                                };
                Controls.Add(btnDelete);
                propertySheet.AddButton(btnDelete);
            }

            btnOk = new Button { ID = "btnOk", CssClass = "ms-ButtonHeightWidth", Text = LocalizationHelper.GetString("wss", "multipages_okbutton_text"), UseSubmitBehavior = false };
            Controls.Add(btnOk);
            propertySheet.AddButton(btnOk);

            btnCancel = new Button { ID = "btnCancel", CssClass = "ms-ButtonHeightWidth", Text = LocalizationHelper.GetString("wss", "multipages_cancelbutton_text"), UseSubmitBehavior = false };
            Controls.Add(btnCancel);
            propertySheet.AddButton(btnCancel);

            formDigest = new FormDigest();
            Controls.Add(formDigest);

            CreateChildControlsForPageTitle();
            CreateChildControlsForPageTitleInTitleArea();            
        }

        protected override void Render(HtmlTextWriter writer)
        {
            propertySheet.RenderControl(writer);

            formDigest.RenderControl(writer);
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            EnsureChildControls();
            btnOk.Click += btnOk_Click;
            btnCancel.Click += btnCancel_Click;

            if (btnDelete != null)
            {
                btnDelete.Click += btnDelete_Click;
            }
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            var web = SPContext.Current.Web;
            var item = QuickLaunchManager.GetQuickLaunchItem(web,
                                                             Convert.ToInt32(Page.Request.QueryString["Id"]));
            web.AllowUnsafeUpdates = true;
            item.Delete(web);
            web.AllowUnsafeUpdates = false;
            
            Page.Response.Redirect(Page.Request.QueryString["Source"], true);
        }

        void btnOk_Click(object sender, EventArgs e)
        {
            var url = txtUrl.Text.Trim();
            if (string.IsNullOrEmpty(url) || url.Equals("http://", StringComparison.InvariantCultureIgnoreCase))
            {
                urlSectionControl.ErrorMessage = HttpContext.GetGlobalResourceObject("wss", "form_empty_value").ToString();
                return;
            }

            var title = txtDescription.Text.Trim();
            if (string.IsNullOrEmpty(title))
            {
                title = url;
            }

            var position = txtPosition.Text.Trim();
            if (string.IsNullOrEmpty(position))
            {
                positionSectionControl.ErrorMessage = HttpContext.GetGlobalResourceObject("wss", "form_empty_value").ToString();
                return;
            }

            int positionValue;

            try
            {
                positionValue = Convert.ToInt32(position);
            }
            catch(Exception)
            {
                positionSectionControl.ErrorMessage = SPResource.GetString(Strings.NumberIncorrectFormat);
                return;
            }

            var web = SPContext.Current.Web;

            if (string.IsNullOrEmpty(Page.Request.QueryString["ParentId"]))
            {
                // Quick Launch Item
                var headingId = 0;
                if (ddlHeading.SelectedIndex > -1)
                {
                    headingId = Convert.ToInt32(ddlHeading.SelectedValue);
                }
                
                if (string.IsNullOrEmpty(Page.Request.QueryString["Id"]))
                {
                    var item = new QuickLaunchItem(title)
                    {
                        Url = url,
                        IsExternalUrl = url.ToLowerInvariant().StartsWith("http://") || url.ToLowerInvariant().StartsWith("https://"),
                        Position = positionValue
                    };

                    QuickLaunchManager.AddNavigationLink(web, item, headingId);
                }
                else
                {
                    var item = QuickLaunchManager.GetQuickLaunchItem(web, Convert.ToInt32(Page.Request.QueryString["Id"]));
                    item.Url = url;
                    item.Title = title;
                    item.IsExternalUrl = url.ToLowerInvariant().StartsWith("http://") ||
                                         url.ToLowerInvariant().StartsWith("https://");
                    item.ParentId = headingId;
                    item.Position = positionValue;
                    item.Update(web);
                }
            }
            else
            {
                // Heading
                if (string.IsNullOrEmpty(Page.Request.QueryString["Id"]))
                {
                    // New Heading
                    var item = new QuickLaunchItem(title)
                                   {
                                       Url = url,
                                       IsExternalUrl = url.ToLowerInvariant().StartsWith("http://") || url.ToLowerInvariant().StartsWith("https://"),
                                       Position = positionValue
                                   };
                    QuickLaunchManager.AddHeading(web, item);
                }
                else
                {
                    var item = QuickLaunchManager.GetQuickLaunchItem(web, Convert.ToInt32(Page.Request.QueryString["Id"]));
                    item.Url = url;
                    item.Title = title;
                    item.IsExternalUrl = url.ToLowerInvariant().StartsWith("http://") || url.ToLowerInvariant().StartsWith("https://");
                    item.Position = positionValue;
                    item.Update(web);
                }
            }

            Page.Response.Redirect(Page.Request.QueryString["Source"], true);
        }

        void btnCancel_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect(Page.Request.QueryString["Source"], true);
        }

        private void CreateChildControlsForPageTitle()
        {
            var control = Page.Master.FindControl("PlaceHolderPageTitle");
            if (control != null)
            {
                if (Page.Request.QueryString["ParentId"] == "1025")
                {
                    pageTitle = string.IsNullOrEmpty(Page.Request.QueryString["Id"])
                                    ? HttpContext.GetGlobalResourceObject("wss", "quiklnch_newcat").ToString()
                                    : HttpContext.GetGlobalResourceObject("wss", "quiklnch_editcat").ToString();
                }
                else
                {
                    pageTitle = string.IsNullOrEmpty(Page.Request.QueryString["Id"])
                                    ? HttpContext.GetGlobalResourceObject("wss", "topnav_newlink").ToString()
                                    : HttpContext.GetGlobalResourceObject("wss", "topnav_editlink").ToString();
                }

                control.Controls.Add(new LiteralControl(pageTitle));
            }
        }

        private void CreateChildControlsForPageTitleInTitleArea()
        {
            var web = SPContext.Current.Web;
            var control = Page.Master.FindControl("PlaceHolderPageTitleInTitleArea");
            if (control != null)
            {
                var lnkSettings = new HyperLink
                                      {
                                          NavigateUrl = string.Format("{0}/_layouts/settings.aspx", web.Url),
                                          Text =
                                              HttpContext.GetGlobalResourceObject("wss", "settings_pagetitle").ToString()
                                      };
                control.Controls.Add(lnkSettings);
                control.Controls.Add(new LiteralControl("&#32;"));
                control.Controls.Add(new ClusteredDirectionalSeparatorArrow());
                control.Controls.Add(new LiteralControl("&#32;"));

                var lnkQuickLaunch = new HyperLink
                                         {
                                             NavigateUrl = string.Format("{0}/QuickLaunchManager.aspx", web.Url),
                                             Text =
                                                 HttpContext.GetGlobalResourceObject("wss", "quiklnch_pagetitle").
                                                 ToString()
                                         };
                control.Controls.Add(lnkQuickLaunch);

                control.Controls.Add(new LiteralControl("&#32;"));
                control.Controls.Add(new ClusteredDirectionalSeparatorArrow());
                control.Controls.Add(new LiteralControl("&#32;"));

                control.Controls.Add(new EncodedLiteral {Text = pageTitle});
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (SPContext.Current.Web.CurrentUser == null)
            {
                SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
            }

            if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.AddAndCustomizePages))
            {
                SPUtility.HandleAccessDenied(new UnauthorizedAccessException());
            }

            var ribbon = SPRibbon.GetCurrent(Page);
            if (ribbon != null)
            {
                ribbon.TrimById("Ribbon.Read");
                ribbon.TrimById("Ribbon.WebPartPage");
            }

            if (!Page.IsPostBack)
            {
                var id = Page.Request.QueryString["Id"];
                if (!string.IsNullOrEmpty(id))
                {
                    EnsureChildControls();
                    var quickLaunchItem = QuickLaunchManager.GetQuickLaunchItem(SPContext.Current.Web, Convert.ToInt32(id));
                    txtUrl.Text = quickLaunchItem.Url;
                    txtDescription.Text = quickLaunchItem.Title;
                    txtPosition.Text = quickLaunchItem.Position.ToString();

                    if (ddlHeading != null && quickLaunchItem.ParentId > 0)
                    {
                        var item = ddlHeading.Items.FindByValue(quickLaunchItem.ParentId.ToString());
                        if (item != null)
                        {
                            item.Selected = true;
                        }
                    }
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            var placeHolderAdditionalPageHead = Page.Master.FindControl("PlaceHolderAdditionalPageHead");
            if (placeHolderAdditionalPageHead != null)
            {
                placeHolderAdditionalPageHead.Controls.Add(new CssRegistration { Name = "layouts.css" });
            }

            if (!Page.ClientScript.IsClientScriptIncludeRegistered("jQuery"))
            {
                Page.ClientScript.RegisterClientScriptInclude("jQuery", "/_layouts/db/jquery-1.4.2.min.js");    
            }

            Page.ClientScript.RegisterStartupScript(GetType(), "Remove WBBody css class",
                                                    "$(document).ready(function(){$('.ms-WPBody').removeClass('ms-WPBody');});",
                                                    true);
        }
    }
}